﻿#动物类
class Animal:
    def __init__(self,name):
        self.name=name

    def speak(self):
        raise NotImplementedError("没有实现")


#申明类
class Dog:
    #类属性: 所有实例共享
    species="can you hello"

    #初始化方法
    def __init__(self,name,age):
        #实例属性
        self.name=name
        self.age=age

    #实例方法
    def bark(self):
        return f"{self.name} says woof!"

    def description(self):
        return f"{self.name} is {self.age} years old"


#继承Dog类
class RedDog(Dog):
    def speak(self):
        return f"{self.name} says meow"


#继承多个类
class MDog(Animal,Dog):
    def speak(self):
        return "super().speak()"


#封装是将数据（属性）和操作数据的方法捆绑在一起的过程：
class BankAccount:
    def __init__(self, account_holder, initial_balance=0):
        self.account_holder = account_holder
        self.__balance = initial_balance  # 私有属性（名称前加双下划线）
    
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return f"存款成功，当前余额: {self.__balance}"
        return "存款金额必须大于0"
    
    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            return f"取款成功，当前余额: {self.__balance}"
        return "取款金额无效或余额不足"
    
    def get_balance(self):
        return self.__balance


# Python 提供了许多特殊方法（以双下划线开头和结尾），用于实现类的特定行为：
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y


#@property 装饰器用于将方法转换为属性，提供更简洁的访问方式：
class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("半径不能为负数")
        self._radius = value
    
    @property
    def area(self):
        return 3.14159 * self._radius ** 2
    
    @property
    def circumference(self):
        return 2 * 3.14159 * self._radius


# 静态方法和类方法
# ​​静态方法​​：不访问实例或类，相当于普通函数
# ​​类方法​​：第一个参数是类本身（cls），而不是实例（self）
class MyClass:
    class_attribute = "类属性"
    
    def __init__(self, value):
        self.instance_attribute = value
    
    @staticmethod
    def static_method():
        return "这是一个静态方法"
    
    @classmethod
    def class_method(cls):
        return f"这是一个类方法，访问类属性: {cls.class_attribute}"
    
    def instance_method(self):
        return f"这是一个实例方法，访问实例属性: {self.instance_attribute}"


#示例1：简单的电商系统
class Product:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity
    
    def total_value(self):
        return self.price * self.quantity
    
    def __str__(self):
        return f"{self.name} - ${self.price} (库存: {self.quantity})"

class ShoppingCart:
    def __init__(self):
        self.items = []
    
    def add_item(self, product, quantity=1):
        if product.quantity >= quantity:
            self.items.append({"product": product, "quantity": quantity})
            product.quantity -= quantity
            print(f"已添加 {quantity} 个 {product.name} 到购物车")
        else:
            print(f"库存不足，无法添加 {product.name}")
    
    def remove_item(self, product_name):
        for item in self.items:
            if item["product"].name == product_name:
                item["product"].quantity += item["quantity"]
                self.items.remove(item)
                print(f"已从购物车移除 {product_name}")
                return
        print(f"购物车中未找到 {product_name}")
    
    def total_cost(self):
        return sum(item["product"].price * item["quantity"] for item in self.items)
    
    def display_cart(self):
        if not self.items:
            print("购物车为空")
            return
        
        print("购物车内容:")
        for item in self.items:
            print(f"{item['product'].name} - {item['quantity']}个 - 小计: ${item['product'].price * item['quantity']}")
        print(f"总计: ${self.total_cost()}")


# 示例2：学生管理系统
class Student:
    def __init__(self, student_id, name, age):
        self.student_id = student_id
        self.name = name
        self.age = age
        self.courses = []
    
    def enroll_course(self, course):
        if course not in self.courses:
            self.courses.append(course)
            course.add_student(self)
            print(f"{self.name} 已注册课程: {course.name}")
        else:
            print(f"{self.name} 已经注册了课程: {course.name}")
    
    def drop_course(self, course):
        if course in self.courses:
            self.courses.remove(course)
            course.remove_student(self)
            print(f"{self.name} 已退选课程: {course.name}")
        else:
            print(f"{self.name} 未注册课程: {course.name}")
    
    def display_info(self):
        print(f"学生ID: {self.student_id}")
        print(f"姓名: {self.name}")
        print(f"年龄: {self.age}")
        print("已注册课程:")
        for course in self.courses:
            print(f"  - {course.name}")

class Course:
    def __init__(self, course_id, name):
        self.course_id = course_id
        self.name = name
        self.students = []
    
    def add_student(self, student):
        if student not in self.students:
            self.students.append(student)
    
    def remove_student(self, student):
        if student in self.students:
            self.students.remove(student)
    
    def display_info(self):
        print(f"课程ID: {self.course_id}")
        print(f"课程名称: {self.name}")
        print("注册学生:")
        for student in self.students:
            print(f"  - {student.name}")



















#创建对象(实例化)
mydog=Dog("dog",16)
print(mydog.bark())
print(mydog.description())
print(mydog.species)

#使用继承
rd=RedDog("red dog",12);
print(rd.speak())

md=MDog("多继承类MDog")
print(md.speak())


#定义一个以父类为入参的方法，便于演示多态
def dog_test(dog):
    print(dog.speak())

#多态 ： 不同类对象对同一个方法进行调用
dogs=[RedDog("a",12),MDog("MD")]
for dog in dogs:
    dog_test(dog)

# 使用封装
account = BankAccount("Alice", 1000)
print(account.deposit(500))  # 存款成功，当前余额: 1500
print(account.withdraw(200))  # 取款成功，当前余额: 1300
# print(account.__balance)  # 错误：无法直接访问私有属性
print(account.get_balance())  # 1300

# 使用特殊方法
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2  # 调用 __add__
print(v3)  # 调用 __str__，输出: Vector(6, 8)
print(v1 == v2)  # 调用 __eq__，输出: False

# 使用属性装饰器
circle = Circle(5)
print(circle.radius)  # 5
print(circle.area)  # 78.53975
print(circle.circumference)  # 31.4159

circle.radius = 10  # 使用setter
print(circle.area)  # 314.159


# 使用静态方法和类方法
print(MyClass.static_method())  # 这是一个静态方法
print(MyClass.class_method())  # 这是一个类方法，访问类属性: 类属性

obj = MyClass("实例值")
print(obj.instance_method())  # 这是一个实例方法，访问实例属性: 实例值


# 简单的电商系统使用示例
product1 = Product("笔记本电脑", 1000, 10)
product2 = Product("鼠标", 25, 50)

cart = ShoppingCart()
cart.add_item(product1, 2)
cart.add_item(product2, 3)
cart.display_cart()

cart.remove_item("鼠标")
cart.display_cart()


# 学生管理系统使用示例
math_course = Course("MATH101", "高等数学")
physics_course = Course("PHYS101", "大学物理")

student1 = Student("S001", "张三", 20)
student2 = Student("S002", "李四", 21)

student1.enroll_course(math_course)
student1.enroll_course(physics_course)
student2.enroll_course(math_course)

print("\n学生信息:")
student1.display_info()

print("\n课程信息:")
math_course.display_info()







